/**
 * 右侧导航
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var util = require("util");
    //require("permission");
    //var storage = require("storage");

    var home = {
        // 初始化左侧树导航
        initTreeMenu: function (trData) {
            var data = trData || this.getFunctionData();
            var menuHtml = '';
            if (data.length > 0) {
                for (var i = 0, l = data.length; i < l; i++) {
                    menuHtml += this.createMenuHtml(data[i]);
                }
            } else {
                return;
            }

            $('#nav').data('menus', data).html(menuHtml);
        },

        clearSelected: function () {
            $('#nav .nav-on').removeClass('nav-on');
        },

        // 创建左侧树导航
        createMenuHtml: function (data) {
            if (data['isVisible'] && data['isVisible'].call() === false) {
                return '';
            }
            var url = data["url"]; //菜单地址
            if (url && url.length > 0) {
                var posIdx = location.hash.indexOf('?');
                var search = (posIdx >= 0 ? location.hash.substr(location.hash.indexOf('?')) : '');
                url = url[0] + search;
            } else {
                url = "javascript:void(0)";
            }

            var hasChildren = data.children && data.children.length > 0;
            var firstLevel = data["level"] === 1;

            var html = '<li id="' + data["id"] + '"' + (hasChildren ? ' hassubmenus = 1 ' : '');

            var navOnCls = firstLevel ? ' nav-selected nav-on' : ' nav-sub-selected nav-sub-on';

            var permissionClass = '';
            if (data['code']) {
                permissionClass = 'permission p-' + data["code"] + ' ' + this._getPermissionClassNames(data.children);
            }

            html += 'class="' + permissionClass + (this.isSelected(data) ? navOnCls : '') + '"';
            html += '><a href="' + url + '" ' + (hasChildren || firstLevel ? 'class="nav-a"' : 'class="nav-sub-a"') + '>';
            if (firstLevel && data['iconCls']) {
                html += '<i class="' + data["iconCls"] + '"></i>';
            }
            html += data["name"] + '</a>';


            if (hasChildren) {
                html += '<ul class="nav-sub">';
                for (var i = 0, l = data.children.length; i < l; i++) {
                    html += this.createMenuHtml(data.children[i]);
                }
                html += '</ul>';
            }

            html += '</li>';
            return html;
        },
        /**
         * 是否选中，本身或者子孙选中时返回true
         * @param navItem
         * @returns {boolean}
         */
        isSelected: function (navItem) {
            var href = location.pathname + location.search;
            var hasHash = location.hash;

            var selected = false;
            var urls = navItem.url;
            if (urls) {
                var urlItem;
                for (var i = 0; urlItem = urls[i]; i++) {
                    //移除hash
                    var hashIndex = urlItem.indexOf("#");
                    var hash = '';
                    if (hashIndex > -1) {
                        hash = urlItem.substring(hashIndex);
                        urlItem = urlItem.substring(0, hashIndex);
                    }

                    if (href.indexOf(urlItem) > -1) {
                        if (hasHash) {
                            if (hash == location.hash || location.hash.indexOf(hash + '?') > -1) {
                                selected = true;
                                break;
                            }
                        } else {
                            selected = true;
                            break;
                        }

                    }

                }
            }

            var children = navItem.children;
            if (children) {
                var childItem;
                for (var i = 0; childItem = children[i]; i++) {
                    var temp = this.isSelected(childItem);
                    if (temp) {
                        selected = temp;
                        break;
                    }
                }
            }

            return selected;
        },

        /**
         * 获取权限类名
         * @param {Array} navItems
         * @returns {string}
         * @private
         */
        _getPermissionClassNames: function (navItems) {
            var classNames = [];

            if (navItems) {
                var item;
                for (var i = 0; item = navItems[i]; i++) {
                    if (item.code) {
                        classNames.push('p-' + item.code);
                    }

                    var childClassNameStr = this._getPermissionClassNames(item.children);
                    if (childClassNameStr) {
                        classNames.push(childClassNameStr);
                    }
                }
            }

            return classNames.join(' ');
        },

        // 初始化导航绑定事件
        initMenuEvent: function () {
            var navPanel = this;
            $(".nav-a").click(function () {
                navPanel.clearSelected();
                var $this = $(this);
                var parent = $this.parent();
                var notSelected = !$this.hasClass('nav-selected');

                if (parent.hasClass('nav-on') && notSelected) {
                    parent.removeClass('nav-on');
                } else {
                    if (notSelected) {
                        //parent.siblings('.nav-on').removeClass('nav-on');
                        parent.addClass('nav-on');
                    }
                }
                setTimeout(function () {
                    if (!parent.attr('hassubmenus')) {
                        navPanel.refresh();
                    }
                }, 0);

            });
            $('.nav').on('click', '.nav-sub-a', function () {
                $('.nav-selected,.nav-sub-on').removeClass('nav-selected').removeClass('nav-sub-on')
                $(this).closest('li').addClass('nav-selected nav-sub-on');
                $(this).closest('.nav-sub').closest('li').addClass('nav-selected');
            });
        },
        // 初始化事件
        initEvents: function (trData) {
            this.initTreeMenu(trData);
            this.initMenuEvent();
        },

        // 初始化
        init: function (trData) {
            var self=this;
            setTimeout(function(){
                self.initEvents(trData);
            },0);

        },
        refresh: function () {
            this.initEvents($('#nav').data('menus'));
        },
        // 获取平台json数据
        getFunctionData: function () {
            var nav = {
                "data": [
                    {
                        "id": "menu_home",
                        "code": "",
                        "name": "合同管理",
                        "level": 1,
                        "iconCls": "glyphicon glyphicon-file icon-none",
                        "url": ["/index.shtml#/contract"],
                        "children": null
                    },
                    {
                        "id": "menu_building",
                        "code": "500301",
                        "name": "合同结算",
                        "level": 1,
                        "iconCls": "glyphicon glyphicon-usd icon-none",
                        "url": ["/index.shtml#/balance"],
                        "children": null
                    },
                    {
                        "id": "menu_building",
                        "code": "500301",
                        "name": "发票管理",
                        "level": 1,
                        "iconCls": "glyphicon glyphicon-tag icon-none",
                        "url": ["/index.shtml#/invoice"],
                        "children": null
                    },                  
                    {
                        "id": "menu_abnormal",
                        "code": "500301",
                        "name": "异常管理",
                        "level": 1,
                        "iconCls": "glyphicon glyphicon-alert icon-none",
                        "children": [
                            {
                                "id": "menu_abnormal_contract",
                                "code": "500301",
                                "name": "违规合同",
                                "level": 2,
                                "iconCls": "icon-data",
                                "url": ["/index.shtml#/violated_contract"],
                                "children": null
                            },
                            {
                                "id": "menu_abnormal_invoice",
                                "code": "500301",
                                "name": "特批发票",
                                "level": 2,
                                "iconCls": "icon-data",
                                "url": ["/index.shtml#/special_approval_invoice"],
                                "children": null
                            },
                            {
                                "id": "menu_abnormal_authorize",
                                "code": "500301",
                                "name": "特批授权",
                                "level": 2,
                                "iconCls": "icon-data",
                                "url": ["/index.shtml#/special_approval_authorize"],
                                "children": null
                            }
                        ]
                    },
                    {
                        "id": "menu_building",
                        "code": "500301",
                        "name": "cms管理",
                        "level": 1,
                        "iconCls": "glyphicon glyphicon-briefcase icon-none",
                        "children": null,
                        "children": [
                            {
                                "id": "menu_abnormal_contract",
                                "code": "500301",
                                "name": "文章发布",
                                "level": 2,
                                "iconCls": "icon-data",
                                "url": ["/api/index.php?r=/cms/article/edit"],
                                "children": null
                            },
                            {
                                "id": "menu_abnormal_invoice",
                                "code": "500301",
                                "name": "文章管理",
                                "level": 2,
                                "iconCls": "icon-data",
                                "url": ["/api/index.php?r=/cms/article/get-list"],
                                "children": null
                            },
                            {
                                "id": "menu_abnormal_authorize",
                                "code": "500301",
                                "name": "目录管理",
                                "level": 2,
                                "iconCls": "icon-data",
                                "url": ["/api/index.php?r=/cms/dir/index"],
                                "children": null
                            },
                            {
                                "id": "menu_abnormal_authorize",
                                "code": "500301",
                                "name": "媒体管理",
                                "level": 2,
                                "iconCls": "icon-data",
                                "url": ["/api/index.php?r=/cms/media/index"],
                                "children": null
                            }                            
                        ]                        
                    },                      
                ]
            }
            return nav.data;
        }
    };

    module.exports = home;
});
